package io.coderyeah.ymcc.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import io.coderyeah.ymcc.domain.PayFlow;
import io.coderyeah.ymcc.domain.PayOrder;
import io.coderyeah.ymcc.mapper.PayOrderMapper;
import io.coderyeah.ymcc.service.IPayFlowService;
import io.coderyeah.ymcc.service.IPayOrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author coderyeah
 * @since 2022-11-04
 */
@Slf4j
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements IPayOrderService {
    @Autowired
    private IPayFlowService flowService;

    @Transactional
    @Override
    public void updateCourseOrderAndPayFlow(PayOrder payOrder, PayFlow payFlow) {
        updateById(payOrder);
        flowService.insert(payFlow);
    }

    @Override
    public PayOrder getByOrderSn(String orderNo) {
        Wrapper<PayOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no", orderNo);
        return selectOne(wrapper);
    }

    @Override
    public void cancelOrder(String orderSn) {
        //1.根据订单号查询支付单
        PayOrder payOrder = getByOrderSn(orderSn);
        if (payOrder != null && payOrder.getPayStatus().equals(PayOrder.PAYING)) {
            //取消支付单
            payOrder.setPayStatus(PayOrder.PAY_CANCEL);
            payOrder.setUpdateTime(new Date());
            updateById(payOrder);
            try {
                //2.支付宝关单
                Factory.Payment.Common().close(orderSn);
                log.info("支付宝关单成功：{}",orderSn);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("支付宝关单失败：{}", e.getMessage());
            }
        }
    }
}
